package com.ct.gd.passport.view.passport;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.lang3.StringUtils;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.ct.gd.passport.R;
import com.ct.gd.passport.common.BaseActivity;
import com.ct.gd.passport.common.constants.UmengVar;
import com.ct.gd.passport.common.mock.HttpConnectClient;
import com.ct.gd.passport.domain.CameraSubmitInfo;
import com.ct.gd.passport.view.widget.CustomHeaderFragment;
import com.umeng.analytics.MobclickAgent;
import com.up91.common.android.async.ILoading;
import com.up91.common.android.async.SimpleAsyncTask;
import com.up91.common.android.helper.ToastHelper;

public class PassportAppCameraActivity extends BaseActivity implements OnClickListener {

	private CustomHeaderFragment mFgHeader;

	EditText mPersonEdt;
	EditText mAddressEdt;
	EditText mCodeEdt;
	EditText mCommentEdt;
	Button mCameraBtn;
	Button mSubmitBtn;

	ImageView mPicView;

	@Override
	protected void onBaseCreate(Bundle savedInstanceState) {
		setContentView(R.layout.passport_app_camera);
	}

	@Override
	protected void initViews() {
		mFgHeader = (CustomHeaderFragment) getSupportFragmentManager().findFragmentById(R.id.header);
		mFgHeader.setCenterText(getString(R.string.passport_submit_camera));

		mCameraBtn = (Button) findViewById(R.id.btn_app_camera_pic);
		mCameraBtn.setOnClickListener(this);

		mSubmitBtn = (Button) findViewById(R.id.btn_app_camera_submit);
		mSubmitBtn.setOnClickListener(this);

		mPicView = (ImageView) findViewById(R.id.iv_app_camera_pic);
		
		mPersonEdt = (EditText)findViewById(R.id.edt_camera_person);
		mAddressEdt = (EditText)findViewById(R.id.edt_camera_addr);
		mCodeEdt = (EditText)findViewById(R.id.edt_camera_code);
		mCommentEdt = (EditText)findViewById(R.id.edt_camera_comment);
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == mCameraBtn.getId()) {
			// 真机使用相机
			mPicView.setImageDrawable(null);
			mPicView.setVisibility(View.GONE);
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			intent.putExtra(MediaStore.EXTRA_OUTPUT,
					Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp1.jpg")));
			intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
			intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, 200*1024L);
			startActivityForResult(intent, 0);
			// 模拟器测试用
//			this.mPicView.setImageResource(R.drawable.icon_info);
//			mPicView.setVisibility(View.VISIBLE);
//			mCameraBtn.setText("重新拍照");
		}

		if (v.getId() == mSubmitBtn.getId()) {
			if (mPicView.getVisibility() == View.GONE) {
				ToastHelper.toast(PassportAppCameraActivity.this, "请拍证件照");
			}else if(StringUtils.isBlank(mPersonEdt.getText())){
				ToastHelper.toast(PassportAppCameraActivity.this, "请填写收件人");
			}else if(StringUtils.isBlank(mAddressEdt.getText())){
				ToastHelper.toast(PassportAppCameraActivity.this, "请填写速递地址");
			}else if(StringUtils.isBlank(mCodeEdt.getText())){
				ToastHelper.toast(PassportAppCameraActivity.this, "请填写邮政编码");
			}else {
				CameraSubmitInfo info = new CameraSubmitInfo();
				info.setExpressName(mPersonEdt.getText().toString());
				info.setExpressAddress(mAddressEdt.getText().toString());
				info.setExpressCode(mCodeEdt.getText().toString());
				info.setComment(mCommentEdt.getText().toString());
				new SendPictureTask(this).execute(info);
				// startActivity(new Intent(this,
				// PassportAppFinishActivity.class));
				// finish();
			}
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		try {
			if (requestCode != 0) {
				return;
			}
			super.onActivityResult(requestCode, resultCode, data);
			transImage( Environment.getExternalStorageDirectory()+"/temp1.jpg", Environment.getExternalStorageDirectory()+"/temp.jpg", 960, 1600, 80);
			Drawable img = Drawable.createFromPath(new File(Environment.getExternalStorageDirectory(), "temp.jpg").getAbsolutePath());
			if (img != null) {
				this.mPicView.setImageDrawable(img);
				mPicView.setVisibility(View.VISIBLE);
				mCameraBtn.setText("重新拍照");
			}
		} catch (Exception e) {
			e.printStackTrace();
			ToastHelper.toast(this, "获取照片失败");
		}
	}
	
	public void transImage(String fromFile, String toFile, int width, int height, int quality)
	{
		try
		{
			Bitmap bitmap = BitmapFactory.decodeFile(fromFile);
			int bitmapWidth = bitmap.getWidth();
			int bitmapHeight = bitmap.getHeight();
			// 缩放图片的尺寸
			float scaleWidth = (float) width / bitmapWidth;
			float scaleHeight = (float) height / bitmapHeight;
			Matrix matrix = new Matrix();
			matrix.postScale(scaleWidth, scaleHeight);
			// 产生缩放后的Bitmap对象
			Bitmap resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, false);
			// save file
			File myCaptureFile = new File(toFile);
			FileOutputStream out = new FileOutputStream(myCaptureFile);
			if(resizeBitmap.compress(Bitmap.CompressFormat.JPEG, quality, out)){
				out.flush();
				out.close();
			}
			if(!bitmap.isRecycled()){
				bitmap.recycle();//记得释放资源，否则会内存溢出
			}
			if(!resizeBitmap.isRecycled()){
				resizeBitmap.recycle();
			}

		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (IOException ex)
		{
			ex.printStackTrace();
		}
	}

	class SendPictureTask extends SimpleAsyncTask<CameraSubmitInfo, Void, String> {
		public SendPictureTask(ILoading loading) {
			super(loading, true);
		}

		@Override
		protected String onLoad(CameraSubmitInfo... params) throws Exception {
			return HttpConnectClient.submitPic(params[0]);
		}

		@Override
		protected void onUI(String result) {
			if(!StringUtils.isBlank(result) && result.indexOf("true")>0){
				MobclickAgent.onEvent(PassportAppCameraActivity.this, UmengVar.PASSPORT_CATPTURE_SUCCESS);
				startActivity(new Intent(PassportAppCameraActivity.this, PassportAppFinishActivity.class));
				finish();
			} else {
				AlertDialog.Builder dialog = new AlertDialog.Builder(PassportAppCameraActivity.this).setTitle(R.string.failure).setMessage(R.string.passport_application_failuere_info);
				dialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
				dialog.show();
			}
		}

	}

}
